package com.iflyun.rabbitmq.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iflyun.rabbitmq.bean.Result;
import com.iflyun.rabbitmq.common.Common;




public class RabbitmqUtils {
	
    private final static Logger logger = LoggerFactory.getLogger(RabbitmqUtils.class);
	
	public static Result CheckQueue(String queueName){	  
        HttpResponse response = null;
        int statusCode = 0;
       
        try {
        	CloseableHttpClient Client =HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(Common.url);
            String up = Common.USERNAME+":"+Common.PASSWORD;
            //设置凭证
            String credentials = Base64.encodeBase64String(up.getBytes("UTF-8"));
            httpGet.setHeader("Authorization","Basic "+credentials);
            response = Client.execute(httpGet);
            //读取响应内容
            BufferedReader breader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuilder responseString = new StringBuilder();
            String line = null;
            while ((line = breader.readLine()) !=null) {
                responseString.append(line);
            }
            breader.close();
            String repsonseStr =responseString.toString();
            statusCode = response.getStatusLine().getStatusCode();
            
            logger.info("statusCode="+statusCode+" repsonseStr =" + repsonseStr);
        
        } catch (Exception e) {
        	logger.info("Could not connect to "+Common.url);
        	logger.error("队列监测异常:",e);
        }
        
        //响应码大于299要么代表错误，要么就是发送给客户端额外的指令
        if(statusCode>299){
            return new Result(statusCode+"", Common.MQ_Queue_Fail, "MQ:"+queueName+" Monitoring  Exception", "MQ:"+queueName+" Monitoring  Exception");
        }
        
        
        return new Result(statusCode+"", Common.MQ_SUCCESS, "MQ:"+queueName+" Monitoring  Success", "MQ:"+queueName+" Monitoring  Exception Success");
	}
	
	public static Map<String,Integer> CheckCustomer(String queueName){
	    Map<String,Integer> map=new HashMap();
		int messages = 0; 
		int messages_ready = 0;
		int messages_unacknowledged = 0;
        HttpResponse response = null;
        String auto_delete = null,durable = null;
        int statusCode = 0;
        try {
        	CloseableHttpClient Client =HttpClients.createDefault();
        	HttpGet httpGet = new HttpGet(Common.curl+queueName);
            String up = Common.USERNAME+":"+Common.PASSWORD;
            //设置凭证
            String credentials = Base64.encodeBase64String(up.getBytes("UTF-8"));
            httpGet.setHeader("Authorization","Basic "+credentials);
            response = Client.execute(httpGet);
            //读取响应内容
            BufferedReader breader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuilder responseString = new StringBuilder();
            String line = null;
            while ((line = breader.readLine()) !=null) {
                responseString.append(line);
            }
            breader.close();
            String repsonseStr =responseString.toString();
            statusCode = response.getStatusLine().getStatusCode();
            logger.info("statusCode="+statusCode+" repsonseStr =" + repsonseStr);
            JSONObject json=JSONObject.parseObject(repsonseStr);
            messages=json.getIntValue("messages");
            messages_ready=json.getIntValue("messages_ready");
            messages_unacknowledged=json.getIntValue("messages_unacknowledged");
            auto_delete = json.getString("auto_delete");
            durable = json.getString("durable");
            map.put("ready", messages_ready);
            map.put("unacknowledged", messages_unacknowledged);
            map.put("auto_delete", "true".equals(auto_delete)?0:1);
            map.put("durable", "true".equals(durable)?0:1);
          //检测auto_delete或者durable属性不对应则警告
        } catch (Exception e) {
        	 logger.error("消费者监测异常",e);
        }
        //响应码大于299要么代表错误，要么就是发送给客户端额外的指令
        if(statusCode>299){
        	logger.warn("Critical:Broker not alive:"+statusCode);
        }
        logger.info("消费者监测过程正常完成");
        return map;

	    
		
	}
		
	
}
